package ar.com.cooker.services.impl;

import java.io.File;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import ar.com.cooker.services.TTSServices;
import ar.com.cooker.services.tts.GoogleTTS;
import ar.com.cooker.services.tts.TTSCookerException;
import ar.com.cooker.services.util.MD5Checksum;
import ar.com.cooker.services.util.PropertyManager;

@Path("/ttsServices")
@Component(value = "ttsServiceBean")
public class TTSServicesImpl implements TTSServices {

	@Override
	@GET
	@Path("/tts/readText/{langCode}/{text}/{callback}")
	@Produces( { "audio/mpeg" })
	public Response readText(@PathParam("langCode")String langCode, @PathParam("text")String text) {
		
		String textChecksum = MD5Checksum.getMD5CheckSum(text);
		String filename = PropertyManager.getInstance().getPathToMp3();
		filename +=File.separator+langCode+"_"+textChecksum+".mp3";		
		GoogleTTS googleTTS = null;
		File f = new File(filename);
		if(!f.exists()){
			googleTTS = new GoogleTTS();
			try {
				googleTTS.generateSoundFile(langCode, text, filename);
			} catch (TTSCookerException e) {
				//TODO: Log the error
				e.printStackTrace();
				return Response.serverError().build();
			}
		}		
		return Response.ok(new File(filename)).type("audio/mpeg")
		.header("content-disposition","filename = text.mp3").build(); 
		
	}
}
